<template>
  <div class="app-container">
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },

    async handleSuccess({ results, header }) {
      console.log('读出来的excel的内容是', results, header)
      try {
        this.tableData = results
        this.tableHeader = header
        // 调用数据转换的函数
        const newData = this.transExcel(results)
        console.log(newData)
        // 发送ajax  请求
        const res = await importEmployee(newData)
        this.$message.success(res.message)
        this.$router.push('/employees')
      } catch (error) {
        this.$message.warning(error)
        console.dir(error)
      }
    },

    // 处理数据，将在xlsx里面得到的数据转换为对应接口想要的数据
    transExcel(results) {
      const mapInfo = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName',
        聘用形式: 'formOfEmployment'
      }
      // 获取到所有的中文key
      const zhKeys = Object.keys(results[0])
      //   console.log('中文', zhKeys)
      // 返回处理过后的数据
      return results.map((item) => {
        // 创建一个对象
        const obj = {}
        // 遍历中文的keys的数组  然后将英文的keys获取到 再往对象里面赋值
        zhKeys.forEach((keys) => {
          const enKey = mapInfo[keys]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            obj[enKey] = new Date(formatExcelDate(item[keys]))
          } else {
            obj[enKey] = item[keys]
          }
        })
        console.log(item)
        return obj
      })
    }
  }
}
</script>
